//
//  SCCommonAlertView.m
//  Shuaiche
//
//  Created by dangshuai on 2018/12/20.
//  Copyright © 2018 ShuaiChe. All rights reserved.
//

#import "SCCommonAlertView.h"
#import "UIView+Line.h"
#import "UILabel+String.h"
#import <Masonry.h>

@implementation SCAlertContentView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        _horizontalPadding = 10;
        _spacing = 25;
    }
    return self;
}

- (void)addView:(UIView *)view {
    [self.stackView addArrangedSubview:view];
}

- (void)insertView:(UIView *)view atIndex:(NSInteger)index {
    [self.stackView insertArrangedSubview:view atIndex:index];
}

- (UIStackView *)stackView {
    if (!_stackView) {
        _stackView = [[UIStackView alloc] init];
        [self addSubview:_stackView];
        _stackView.distribution = UIStackViewDistributionFill;
        _stackView.axis = UILayoutConstraintAxisVertical;
        _stackView.spacing = _spacing;
        _stackView.alignment = UIStackViewAlignmentCenter;
        [_stackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(_spacing);
            make.left.equalTo(self).offset(_horizontalPadding);
            make.right.equalTo(self).offset(-_horizontalPadding);
            make.bottom.equalTo(self).offset(-20);
        }];
//        _stackView.translatesAutoresizingMaskIntoConstraints = NO;
//        [_stackView.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:_horizontalPadding].active = YES;
//        [_stackView.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-_horizontalPadding].active = YES;
//        [_stackView.topAnchor constraintEqualToAnchor:self.topAnchor constant:_spacing].active = YES;
//        [_stackView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-20].active = YES;
    }
    return _stackView;
}

- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    if (self.color) {
        CGContextSetFillColorWithColor(context, self.color.CGColor);
    } else {
        CGContextSetGrayFillColor(context, 0.0f, NO);
    }

    CGRect allRect = self.bounds;
    CGFloat y = _offsetY == 0 ?: (_offsetY + _spacing);
    CGRect boxRect = CGRectMake(0, y ,allRect.size.width, allRect.size.height - y);
    float radius = self.cornerRadius;
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect));
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0);
    CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0);
    CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0);
    CGContextClosePath(context);
    CGContextFillPath(context);
    UIGraphicsPopContext();
}

@end


@interface SCCommonAlertView ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *otherButton;
@property (nonatomic, strong) UIView *buttonView;
@property (nonatomic, assign) BOOL shouldHideWhenTapBack;
@property (nonatomic, strong) NSMutableArray *buttonsArray;

@property (nonatomic, copy) void(^block)(NSInteger idx);

@end

#define kContentWidth (CGRectGetWidth([UIScreen mainScreen].bounds) - 100)
static CGFloat kTitleHeight = 40.f;
@implementation SCCommonAlertView {
    
    UIView *_contentView;
    SCAlertContentView *_alertContent;
    
    NSString *_title;
    NSString *_message;
    NSString *_cancelTitle;
    NSString *_otherTitle;
    
    NSString *_tip;
    NSString *_mainTitle;
    
    CGFloat _titleHeight;
    CGFloat _messageMinimumHeight;
    CGFloat _buttonHeight;
}

- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
               cancelBtnTitle:(NSString *)cancelTitle
                otherBtnTitle:(NSString *)otherBtnTitle
              clickIndexBlock:(void (^)(NSInteger))block {
    self = [super init];
    if (self) {
        _title = title;
        _message = message;
        _cancelTitle = cancelTitle;
        _otherTitle = otherBtnTitle;
        self.backgroundColor = SC_RGBA(0, 0, 0, 0.5);
        _messageMinimumHeight = 65;
        if (block) {
            self.block = [block copy];
        }
        [self createSubview];
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
                      mainAct:(NSString *)main
                     otherAct:(NSString *)other
                  handleBlock:(void(^)(NSInteger index))block {
    return [self initWithTitle:title message:message tip:nil mainAct:main otherAct:other handleBlock:block];
}

- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message
                          tip:(NSString *)tip
                      mainAct:(NSString *)main
                     otherAct:(NSString *)other
                  handleBlock:(void(^)(NSInteger index))block {
    self = [super init];
    if (self) {
        
        _titleAlignment = 1;
        _messageAlignment = 1;
        
        _title = title;
        _message = message;
        _mainTitle = main;
        _tip = tip;
        _otherTitle = other;
        self.backgroundColor = SC_RGBA(0, 0, 0, 0.5);
        if (block) {
            self.block = [block copy];
        }
        [self createContentView];
    }
    return self;
}

+ (instancetype)showTitle:(NSString *)title
                  message:(NSString *)message
                  mainAct:(NSString *)main
                 otherAct:(nullable NSString *)other
              handleBlock:(void(^)(NSInteger index))block {
    SCCommonAlertView *alert = [[SCCommonAlertView alloc] initWithTitle:title message:message mainAct:main otherAct:other handleBlock:block];
    [alert show];
    return alert;
}

+ (instancetype)showWithTitle:(NSString *)title message:(NSString *)message cancelBtnTitle:(NSString *)cancelTitle otherBtnTitle:(NSString *)otherBtnTitle clickIndexBlock:(void(^)(NSInteger index))block {
    SCCommonAlertView *alert = [[SCCommonAlertView alloc] initWithTitle:title message:message cancelBtnTitle:cancelTitle otherBtnTitle:otherBtnTitle clickIndexBlock:block];
    [alert show];
    return alert;
}

- (void)show {
    [self showWithView:[UIApplication sharedApplication].keyWindow];
}

- (void)showWithView:(UIView *)view {
    self.frame = view.bounds;
    self.alpha = 0;
    [view addSubview:self];
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1;
    }];
}

- (void)hideView {
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (UIButton *)buttonWithIndex:(NSInteger)index {
    if (index < _buttonsArray.count) {
        return _buttonsArray[index];
    }
    return nil;
}

- (void)setTitleColor:(UIColor *)color forButtonAtIndex:(NSInteger)index {
    UIButton *btn = [self buttonWithIndex:index];
    [btn setTitleColor:color forState:0];
}
- (void)setMessageColor:(UIColor *)color {
    _messageLabel.textColor = color;
}
- (void)addButtonClickBlock:(void(^)(NSInteger index))block {
    self.block = [block copy];
}

- (void)setTitleAlignment:(NSTextAlignment)titleAlignment {
    _titleAlignment = titleAlignment;
    _titleLabel.textAlignment = titleAlignment;
}

- (void)setMessageAlignment:(NSTextAlignment)messageAlignment {
    _messageAlignment = messageAlignment;
    _messageLabel.textAlignment = _messageAlignment;
}

- (void)createContentView {
    
    _alertContent = [[SCAlertContentView alloc] init];
    _alertContent.color = [UIColor whiteColor];
    _alertContent.cornerRadius = 6.0;
    [self addSubview:_alertContent];
    [_alertContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@270);
    }];
//    _alertContent.translatesAutoresizingMaskIntoConstraints = NO;
//    [_alertContent.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = YES;
//    [_alertContent.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = YES;
//    [_alertContent.widthAnchor constraintEqualToConstant:270].active = YES;
    
    if (_title.length) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = _titleAlignment;
        _titleLabel.textColor = SC_TextBlack_Primary;
        _titleLabel.font = [UIFont systemFontOfSize:16];
        _titleLabel.text = _title;
        [_alertContent addView:_titleLabel];
    }
    
    if (_message.length) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.textAlignment = _messageAlignment;
        _messageLabel.textColor = SC_TextBlack_Secondary;
        _messageLabel.font = [UIFont systemFontOfSize:14];
        _messageLabel.numberOfLines = 0;
        [_messageLabel setText:_message lineSpacing:3];
        [_alertContent addView:_messageLabel];
    }
    
    if (_tip.length) {
        UILabel *tipLabel = [[UILabel alloc] init];
        tipLabel.textAlignment = 1;
        tipLabel.textColor = SC_TextBlack_Third;
        tipLabel.font = [UIFont systemFontOfSize:12];
        tipLabel.numberOfLines = 0;
        tipLabel.text = _tip;
        [_alertContent addView:tipLabel];
    }
    
    if (_mainTitle.length) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        button.tag = 0;
        [button setTitleColor:SC_TextBlack_Primary forState:0];
        [button addTarget:self action:@selector(actionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 6;
        button.layer.backgroundColor = SC_Color_Tint.CGColor;
        [button.heightAnchor constraintEqualToConstant:40].active = YES;
        [button.widthAnchor constraintEqualToConstant:230].active = YES;
        [button setTitle:_mainTitle forState:0];
        [_alertContent addView:button];
    }
    
    if (_otherTitle.length) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        button.tag = 1;
        [button setTitleColor:SC_TextBlack_Third forState:0];
        [button addTarget:self action:@selector(actionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button.heightAnchor constraintEqualToConstant:20].active = YES;
        [button.widthAnchor constraintEqualToConstant:230].active = YES;
        [button setTitle:_otherTitle forState:0];
        [_alertContent addView:button];
    }
}

- (void)addTopImageView:(NSString *)imageName {
    
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//    CGFloat half = image.size.height / 2;
//    imageView.layer.cornerRadius = half;
//    imageView.layer.masksToBounds = YES;
//    _alertContent.offsetY = half;
    [_alertContent insertView:imageView atIndex:0];
}

- (void)createSubview {
    CGFloat subviewWidth = kContentWidth - 40;
    _contentView = [[UIView alloc] init];
    _contentView.layer.backgroundColor = [UIColor whiteColor].CGColor;
    _contentView.layer.cornerRadius = 4.0;
    [self addSubview:_contentView];
    
    _titleHeight = 0;
    if (_title.length) {
        _titleHeight = kTitleHeight;
        self.titleLabel.text = _title;
    }
    
    if (_message.length) {
        self.messageLabel.text = _message;
        CGSize maximumLabelSize = CGSizeMake(subviewWidth, MAXFLOAT);
        CGSize expectSize = [_messageLabel sizeThatFits:maximumLabelSize];
        if (_titleHeight == 0) {_messageMinimumHeight = 80;}
        _messageLabel.frame = CGRectMake(20, _titleHeight, subviewWidth, MAX(expectSize.height + 40, _messageMinimumHeight));
    }
    
    NSMutableArray *arry = [NSMutableArray arrayWithCapacity:0];
    if (_cancelTitle) {
        [arry addObject:_cancelTitle];
    }
    
    if (_otherTitle) {
        [arry addObject:_otherTitle];
    }
    
    CGFloat h = CGRectGetHeight(_messageLabel.bounds) + CGRectGetMaxY(_titleLabel.frame);
    if (arry.count) {
        _buttonHeight = 45.f;
        _buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, h, kContentWidth, _buttonHeight)];
        [_buttonView addLineWithFrame:CGRectMake(0, 0, kContentWidth, 0.5)];
        [_contentView addSubview:_buttonView];
        CGFloat bw = floor(kContentWidth/(CGFloat)arry.count);
        for (int i = 0; i < arry.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(bw * i, 0, bw, _buttonHeight);
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            [button setTitleColor:SCColor(0x222222) forState:0];
            [button setTitle:arry[i] forState:0];
            [button addTarget:self action:@selector(actionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = i;
            [_buttonView addSubview:button];
            [self.buttonsArray addObject:button];
            if (i > 0) {
                [button addLineWithFrame:CGRectMake(0, 0, 0.5, _buttonHeight)];
                [button setTitleColor:SC_TextYellow forState:0];
            }
        }
    }

    h += _buttonHeight;
    _contentView.bounds = CGRectMake(0, 0, kContentWidth, h);
    _contentView.center = CGPointMake(kSCScreenWidth / 2.f, kSCScreenHeight/2.f);
}

- (void)actionButtonClick:(UIButton *)sender {
    [self endEditing:YES];
    if (self.block) {
        self.block(sender.tag);
    }
    if (!self.alwaysShow) {
        [self hideView];
    }
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kContentWidth, _titleHeight)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.font = [UIFont systemFontOfSize:16];
        [_contentView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)messageLabel {
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.textColor = SC_TextBlack_Primary;
        _messageLabel.font = [UIFont systemFontOfSize:14];
        _messageLabel.numberOfLines = 0;
        [_contentView addSubview:_messageLabel];
    }
    return _messageLabel;
}

- (NSMutableArray *)buttonsArray {
    if (!_buttonsArray) {
        _buttonsArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _buttonsArray;
}

- (void)insertCustomView:(UIView *)customeView atIndex:(NSInteger)index {
    [customeView.widthAnchor constraintEqualToConstant:230].active = YES;
    [customeView.heightAnchor constraintEqualToConstant:40].active = YES;
    [_alertContent insertView:customeView atIndex:index];
}

- (void)insertCustomViewHeight:(UIView *)customeView atIndex:(NSInteger)index {
    [customeView.widthAnchor constraintEqualToConstant:230].active = YES;
    [_alertContent insertView:customeView atIndex:index];
}

- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler {
    UITextField *textField = [[UITextField alloc] init];
    textField.font = SC_FONT(14);
    textField.textColor = SC_TextBlack_Primary;
    textField.frame = CGRectMake(25, _titleHeight + 25, kSCScreenWidth - 150, 40);
    [_contentView addSubview:textField];
    if (configurationHandler) {
        configurationHandler(textField);
    }
    CGRect button_fr = _buttonView.frame;
    button_fr.origin.y = CGRectGetMaxY(textField.frame) + 20;
    _buttonView.frame = button_fr;
    _contentView.bounds = CGRectMake(0, 0, kContentWidth, button_fr.origin.y + _buttonHeight);
    _contentView.center = CGPointMake(kSCScreenWidth / 2.f, kSCScreenHeight/2.f);
}
- (void)addTextFieldWithMessage:(NSString *)message configurationHandler:(void (^)(UITextField *textField, UILabel *messageLab))configurationHandler alwaysShow:(BOOL)noHide{
    self.alwaysShow = noHide;
    UITextField *textField = [[UITextField alloc] init];
    UILabel *tipLab = [[UILabel alloc] init];
    textField.font = SC_FONT(14);
    textField.textColor = SC_TextBlack_Primary;
    textField.frame = CGRectMake(20, 30, 230, 40);
    if (configurationHandler) {
        configurationHandler(textField, tipLab);
    }
    [_alertContent addSubview:textField];
    [_alertContent mas_makeConstraints:^(MASConstraintMaker *make) {
           make.center.equalTo(self);
           make.width.equalTo(@270);
           make.height.equalTo(@260);
    }];
    [_alertContent.stackView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_alertContent).offset(90);
    }];
    [_alertContent setNeedsDisplay];
}
- (NSArray<UITextField *> *)textFields {
    NSArray *array = _contentView.subviews.copy;
    NSMutableArray *marray = [NSMutableArray arrayWithCapacity:0];
    for (UIView *v in array) {
        if ([v isKindOfClass:UITextField.class]) {
            [marray addObject:v];
        }
    }
    return marray;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_hideWhenTapBack) {
        UITouch * touch = [touches anyObject];
        CGPoint point = [touch locationInView:self];
        if (!CGRectContainsPoint(_alertContent.frame, point)) {
            _shouldHideWhenTapBack = YES;
        }
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_hideWhenTapBack && _shouldHideWhenTapBack) {
        _shouldHideWhenTapBack = NO;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_hideWhenTapBack && _shouldHideWhenTapBack) {
        _shouldHideWhenTapBack = NO;
        [self hideView];
    }
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_hideWhenTapBack && _shouldHideWhenTapBack) {
        _shouldHideWhenTapBack = NO;
        [self hideView];
    }
}

@end
